package com.lemon.smartsafetynew.ui.fragment.base;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.ldzs.recyclerlibrary.Mode;
import com.ldzs.recyclerlibrary.PullToRefreshRecyclerView;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.app.RefreshType;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.listener.HttpEventListener;
import com.lemon.smartsafety.listener.PullLoadMoreListener;
import com.lemon.smartsafety.listener.PullRefreshListener;
import com.lemon.smartsafety.utils.common.FileUtil;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.view.list.MultiStateView;
import com.lemon.smartsafetynew.util.common.MyIntent;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import kale.adapter.LemonRcvAdapter;
import okhttp3.Call;

/**
 * Created by Cooliean on 16/3/20.
 * L 是 List的泛型
 * H 是Http返回的泛型
 */
public abstract class BasePullToRefreshAddTitleFragment<L, H extends List> extends BaseFragment implements HttpEventListener<H>, PullRefreshListener, PullLoadMoreListener {

    @Bind(R.id.tv_title_count)
    public TextView tvTitleCount;
    @Bind(R.id.ll_tilte)
    public LinearLayout llTilte;
    @Bind(R.id.tv_title)
    public TextView tvTitle;
    @Bind(R.id.tv_record_title)
    public TextView tvRecordTitle;
    @Bind(R.id.ll_yellow_title)
    public LinearLayout llYellowTitle;
    @Bind(R.id.right_labels)
    FloatingActionsMenu rightLabels;
    @Bind(R.id.mRefreshContainer)
    LinearLayout mRefreshContainer;

    private LoggerHelper loggerHelper = new LoggerHelper(BasePullToRefreshAddTitleFragment.class);

    @Bind(R.id.pullToRefreshRecyclerView)
    public PullToRefreshRecyclerView mPullToRefreshRecyclerView;

    @Nullable
    @Bind(R.id.multiStateView)
    public MultiStateView mMultiStateView;


    @Nullable
    @Bind(R.id.top_line)
    protected View mTopLine;


    @Nullable
    @Bind(R.id.float_button)
    protected FloatingActionButton fab;

    protected int currentPage = Constants.DEFAULT_FIRST_PAGE_NUMBER;

    protected int pageSize = Constants.PAGE_SIZE;

    public H mDataList = (H) new ArrayList<>();

    protected LemonRcvAdapter<L> mAdapter;

    protected boolean isVisible;

    @Override
    protected void initViews() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(IApplication.context(), LinearLayoutManager.VERTICAL, false);
        mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
        mPullToRefreshRecyclerView.setLayoutManager(layoutManager);
        mAdapter = getLemonAdapter();
        mPullToRefreshRecyclerView.setAdapter(mAdapter);
        mPullToRefreshRecyclerView.setOnPullUpToRefreshListener(new PullToRefreshRecyclerView.OnPullUpToRefreshListener() {
            @Override
            public void onRefresh() {
                currentPage = Constants.DEFAULT_FIRST_PAGE_NUMBER;
                onPullRefresh();
            }
        });
        mPullToRefreshRecyclerView.setOnPullDownToRefreshListener(new PullToRefreshRecyclerView.OnPullDownToRefreshListener() {
            @Override
            public void onRefresh() {
                onLoadMore();
            }
        });

        mMultiStateView.setErrorRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                mPullToRefreshRecyclerView.beginRefreshing();
            }
        });

        //add by Andrew.yin 2017/10/20 begin 数据为空时
        mMultiStateView.setEmptyRetryListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                mPullToRefreshRecyclerView.beginRefreshing();
            }
        });
        //add by Andrew.yin 2017/10/20 end
    }

    public void doPullRefresh() {
        mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
        mPullToRefreshRecyclerView.beginRefreshing();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (goRefreshOnCreate()) {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            mPullToRefreshRecyclerView.beginRefreshing();
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_refresh_title;
    }

    @Override
    protected void getBaseArguments() {

    }

    /**
     * 是否在视图创建好后，就自动下来刷新
     *
     * @return
     */
    public abstract boolean goRefreshOnCreate();


    /**
     * 设置页面的Adapter
     *
     * @return
     */
    public abstract LemonRcvAdapter<L> getLemonAdapter();

    /**
     * 给请求设置一个Tag 可以过滤OnEvent的处理
     *
     * @return
     */
    public abstract String getHttpTag();


    /**
     * 数据请求事件
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent<H> event) {
        if (!getHttpTag().equals(event.getTag())) {
            return;
        }
        if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {
        } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow() && mPullToRefreshRecyclerView != null) {
            RefreshType type = (RefreshType) event.getOther();
            if (RefreshType.REFRESH == type) {
                mPullToRefreshRecyclerView.onRefreshComplete();
            } else {
                mPullToRefreshRecyclerView.setFooterComplete();
            }
            if (Constants.Result.SUCCESS == event.getEventResult()) {
                if (RefreshType.REFRESH == type) {
                    httpRefresh(event.getObj());
                } else {
                    httpLoadMore(event.getObj());
                }
                currentPage++;
            } else if (Constants.Result.ERROR == event.getEventResult()) {
                if (RefreshType.REFRESH == type) {
                    httpRefreshError(event.getMsg());
                } else {
                    httpLoadMoreError(event.getMsg());
                }
            }

        }
    }

    //刷新标题数目
    public abstract void onDataList(H data);

    @Override
    public void httpRefresh(H data) {
        onDataList(data);
        if (data != null && !data.isEmpty()) {
            mMultiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
            if (data.size() < pageSize) {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
                //mPullToRefreshRecyclerView.setFooterComplete();
            } else {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.BOTH);
            }
            mDataList.clear();
            mAdapter.notifyDataSetChanged();
            mAdapter.addItems(data);
        } else {
            //mMultiStateView.setViewState(MultiStateView.VIEW_STATE_EMPTY); delete by Andrew.yin 2017/10/20
            if (!mDataList.isEmpty()) {
                mDataList.clear();
                mAdapter.notifyDataSetChanged();
            }
            mMultiStateView.setEmptyTip("暂无更多数据 : )");
        }
    }

    @Override
    public void httpLoadMore(H data) {
        if (data != null && !data.isEmpty()) {
            if (data.size() < pageSize) {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.PULL_FROM_START);
                mPullToRefreshRecyclerView.setFooterComplete();
            } else {
                mPullToRefreshRecyclerView.setRefreshMode(Mode.BOTH);
            }
            mAdapter.addItems(data);
        }
    }

    @Override
    public void httpRefreshError(String msg) {
        mHUDUtil.showErrorTip(msg);
        mMultiStateView.setErrorTip(msg);
    }

    @Override
    public void httpLoadMoreError(String msg) {
        //mHUDUtil.showErrorTip(msg);
    }


    //add by Andrew.yin 2017/7/31 begin
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInvisible();
        }
    }

    protected void onVisible() {
    }

    protected void onInvisible() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    //add by Andrew.yin 2017/7/31 end
}
